using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Super
{
	/// <summary>s
	/// 可序列化保存字典
	/// SO保存字典数据，重启编辑器后数据会置空，用此结构代替
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <typeparam name="V"></typeparam>
	[Serializable]
	public class SerializeDict<T, V>
	{
		public string dictJson = "";
		private Dictionary<T, V> dict;
		public Dictionary<T, V> Dict
		{
			get
			{
				if (dict == null)
				{
					if (string.IsNullOrEmpty(dictJson))
					{
						dict = new Dictionary<T, V>();
					}
					else
					{
						dict = JsonConvert.DeserializeObject<Dictionary<T, V>>(dictJson);
					}
				}
				return dict;
			}
		}

		public Dictionary<T, V>.ValueCollection Values
		{
			get
			{
				return Dict.Values;
			}
		}
		
		public Dictionary<T, V>.KeyCollection Keys
		{
			get
			{
				return Dict.Keys;
			}
		}
		
		public int Count
		{
			get
			{
				return Dict.Count;
			}
		}

		public void Add(T key, V value, bool saveData = false)
		{
			Dict[key] = value;
			if (saveData)
				SaveData();
		}

		public void Remove(T key, bool saveData = false)
		{
			Dict.Remove(key);
			if (saveData)
				SaveData();
		}

		public void Clear(bool saveData = false)
		{
			Dict.Clear();
			if (saveData)
				SaveData();
		}

		public bool ContainsKey(T key)
		{
			return Dict.ContainsKey(key) ? true : false;
		}

		public V this[T key]
		{
			get
			{
				if (ContainsKey(key))
					return Dict[key];
				return default(V);
			}

			set
			{
				Dict[key] = value;
				SaveData();
			}
		}

		// 升序
		public void OrderByKey()
		{
			dict.OrderBy((source)=> source.Key);
		}
		
		public void SaveData()
		{
			dictJson = JsonConvert.SerializeObject(Dict);
		}
	}

}
